import { waitObject } from "../util/wait.js";

/*!
 * 粘贴带标题的 URL 时，处理成 Markdown 的 URL 格式
 */
export async function injectToPasteLink() {
    if (!navigator.clipboard) {
        (console.warn ?? console.log)("Clipboard API is not supported.");
    }

    const editor = await waitObject(() => document.querySelector(".CodeMirror")?.CodeMirror);

    editor.on("paste", async (cm, e) => {
        const md = getLinkMarkdown(e);
        if (md) {
            e.preventDefault();
            const doc = cm.getDoc();
            doc.replaceSelection(md);
        }
    });

    function getLinkMarkdown(e) {
        const data = e.clipboardData;
        const html = data.getData("text/html");
        const div = document.createElement("div");
        div.innerHTML = html;
        if (div.childElementCount !== 1) { return; }
        const a = div.children[0];
        if (a.tagName !== "A") { return; }
        return `[${a.innerText}](${a.href})`;
    }
}
